iT邦幫忙

1

Leetcode 270. ( Closest Binary Search Tree Value )

  • 分享至 

  • xImage
  •  

In time, you will call me master -- Star Wars
https://leetcode.com/problems/closest-binary-search-tree-value/

  • Description (Easy)
    • Given a non-empty binary search tree and a target value
    • Find Closest value to target
  • Solution
    • maintain a parent_val to store parent value
    • maintain a closest_val to store closest node
  • Code
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def closestValue(self, root: TreeNode, target: float) -> int:
        target = round(target)
        parent_val = closest_val = root.val
        while root:
            if root.val < target:
                root = root.right
            elif root.val > target:
                root = root.left
            else:
                return target
            if root != None:
                if abs(root.val-target) < abs(parent_val-target):
                    closest_val = root.val
                parent_val = root.val
        return closest_val

https://ithelp.ithome.com.tw/upload/images/20200620/20116751Me2VVlEglf.png


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言